<template>
  <div class="pay">
    <div class="main">
      <div class="payHeader">
        支付总金额
        <span>￥ {{payInfo.price}}</span>
      </div>
      <div class="payBody">
        <h1>微信支付</h1>
        <el-row type="flex" justify="space-around" align="middle">
          <div class="qrCode">
            <canvas ref="qr" width="200" height="200"></canvas>
            <p>请使用微信扫一扫</p>
            <p>扫描二维码支付</p>
          </div>
          <img src="http://157.122.54.189:9093/images/wx-sweep2.jpg" alt />
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import QRCode from "qrcode";
export default {
  data() {
    return {
      payInfo: {},
      timer: null
    };
  },
  watch: {
    "$store.state.user.userInfo.token": {
      handler() {
        if (this.$store.state.user.userInfo.token) {
          this.getPayInfo();
        }
      },
      immediate: true
    }
  },
  methods: {
    //获取订单
    getPayInfo() {
      this.$axios({
        url: "/airorders/" + this.$route.query.id,
        headers: {
          Authorization: "Bearer " + this.$store.state.user.userInfo.token
        }
      }).then(res => {
        this.payInfo = res.data;
        QRCode.toDataURL(this.$refs.qr, res.data.payInfo.code_url);
        this.timer = setInterval(() => {
          this.checking();
        }, 2000);
      });
    },

    //检查订单
    checking() {
      this.$axios({
        url: "/airorders/checkpay",
        method: "post",
        headers: {
          Authorization: "Bearer " + this.$store.state.user.userInfo.token
        },
        data: {
          id: this.payInfo.id,
          nonce_str: this.payInfo.price,
          out_trade_no: this.payInfo.orderNo
        }
      }).then(res => {
        if (res.data.trade_state == "SUCCESS") {
          clearInterval(this.timer);
          this.$message.success(res.data.statusTxt);
        }
      });
    }
  },
  beforeDestroy() {
    clearInterval(this.timer);
    this.timer = null;
  }
};
</script>

<style lang="less" scoped>
.pay {
  background: #f5f5f5;
  padding: 20px 0;
  .main {
    width: 1000px;
    margin: 0 auto;
    .payHeader {
      text-align: right;
      span {
        font-size: 28px;
        color: #ff4500;
      }
    }
    .payBody {
      background: #fff;
      border-top: 5px solid #ffa500;
      margin-top: 5px;
      padding: 30px;
      .qrCode {
        border: 1px solid #ddd;
        padding: 15px;
        height: fit-content;
        text-align: center;
        p {
          line-height: 2;
        }
      }
    }
  }
}
</style>